package com.xxkj.drugtraceability.ui.hascollected

import android.app.DatePickerDialog
import android.content.Intent
import android.text.Editable
import android.text.TextWatcher
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.widget.LinearLayout
import android.widget.PopupWindow
import android.widget.TextView
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
import com.google.gson.Gson
import com.xxhis.drugtraceability.base.BaseFragment
import com.xxhis.refactor.ext.dp2px
import com.xxkj.drugtraceability.R
import com.xxkj.drugtraceability.base.BaseVMFragment
import com.xxkj.drugtraceability.bean.OneOutRequest
import com.xxkj.drugtraceability.bean.OneRequest
import com.xxkj.drugtraceability.databinding.FragmentOneBinding
import com.xxkj.drugtraceability.databinding.FragmentThreeBinding
import com.xxkj.drugtraceability.ext.clickN
import com.xxkj.drugtraceability.ui.tracdetail.TracDetailActivity
import com.xxkj.drugtraceability.utils.toast
import org.koin.androidx.viewmodel.ext.android.sharedViewModel
import java.util.*

/**
 * author: zhoujingjin
 * created on: 2024/9/18 16:51
 * description:
 */
class ThreeFragment:BaseVMFragment<FragmentThreeBinding>(R.layout.fragment_three) {
    val viewModel by sharedViewModel<HasCollectedViewModel>()
    lateinit var linearLayoutManager: LinearLayoutManager
    lateinit var threeAdapter: ThreeAdapter
    var tradeType = "1"
    companion object {
        fun newInstance(): ThreeFragment {
            val fragment = ThreeFragment()
            return fragment
        }
    }
    override fun initView() {
        binding.apply {
            linearLayoutManager =  LinearLayoutManager(requireContext())
            recyclerView.layoutManager = linearLayoutManager
            threeAdapter = ThreeAdapter {
                var isRollBackTrade = binding.tvDepart.text == "退药采集"
                startActivity(Intent(requireContext(),TracDetailActivity::class.java).putExtra("data",
                    Gson().toJson(it)).putExtra("tradeType",tradeType).putExtra("dataType","2").putExtra("isRollBackTrade",isRollBackTrade))
            }
            recyclerView.adapter = threeAdapter
            etInput.addTextChangedListener(object : TextWatcher {
                override fun afterTextChanged(s: Editable?) {
                    viewModel.getTracCodeList2(endDate,startDate,"2","",s.toString(),"",tradeType,"")
                }

                override fun beforeTextChanged(
                    s: CharSequence?,
                    start: Int,
                    count: Int,
                    after: Int
                ) {
                }

                override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                }
            })

            flDepart.clickN {
                showPopupWindow(flDepart)
            }
        }
    }

    override fun initData() {
        viewModel.getTracCodeList2(endDate,startDate,"2","","","","1","")
    }

    override fun startObserve() {
        viewModel.threeList.observe(this, Observer {
            if (it.isEmpty()){
                threeAdapter.setEmptyView(R.layout.layout_nodata)
            }
            threeAdapter.setList(it)
        })
    }
    private fun showPopupWindow(anchorView: View) {
        // 获取 PopupWindow 的布局
        val popupView = LayoutInflater.from(requireContext()).inflate(R.layout.popup_layout, null)

        // 创建 PopupWindow 对象
        val popupWindow = PopupWindow(
            popupView,
            requireActivity().dp2px(150),
            LinearLayout.LayoutParams.WRAP_CONTENT,
            true // 点击外部是否关闭 PopupWindow
        )

        // 设置背景和点击外部可关闭
//        popupWindow.setBackgroundDrawable(ContextCompat.getDrawable(requireContext(), R.drawable.popup_background))
        popupWindow.isOutsideTouchable = true

        // 获取布局中的组件，设置监听器等
        val tv1 = popupView.findViewById<TextView>(R.id.tv_1)
        val tv2 = popupView.findViewById<TextView>(R.id.tv_2)
        tv1.text = "发药采集"
        tv2.text = "退药采集"
        tv1.clickN {
            if (tradeType!="1"){
                tradeType = "1"
                binding.tvDepart.text = "发药采集"
                viewModel.getTracCodeList2(endDate,startDate,"2","",binding.etInput.text.toString(),"",tradeType,"")
            }
            popupWindow.dismiss()

        }
        tv2.clickN {
            if (tradeType!="2"){
                tradeType = "2"
                binding.tvDepart.text = "退药采集"
                viewModel.getTracCodeList2(endDate,startDate,"2","",binding.etInput.text.toString(),"",tradeType,"")
            }
            popupWindow.dismiss()
        }
        // 显示 PopupWindow
        popupWindow.showAsDropDown(anchorView, 0, 0, Gravity.BOTTOM)
    }

    private val calendarStart = Calendar.getInstance()
    private  val calendarEnd = Calendar.getInstance()
    private var startDatePicker : DatePickerDialog? = null
    private var endDatePicker : DatePickerDialog? = null
    private var startDate:String="${calendarStart.get(Calendar.YEAR)}-${calendarStart.get(
        Calendar.MONTH) + 1}-${calendarStart.get(Calendar.DAY_OF_MONTH)}"
    private var endDate:String="${calendarEnd.get(Calendar.YEAR)}-${calendarEnd.get(
        Calendar.MONTH) + 1}-${calendarEnd.get(Calendar.DAY_OF_MONTH)}"
    fun showDatePicker(){
        if (startDatePicker==null){
            startDatePicker = DatePickerDialog(
                requireContext(),
                { _, year, monthOfYear, dayOfMonth ->
                    calendarStart.set(year, monthOfYear, dayOfMonth)
                    if (endDatePicker==null){
                        endDatePicker = DatePickerDialog(
                            requireContext(),
                            { _, endYear, endMonthOfYear, endDayOfMonth ->
                                calendarEnd.set(endYear, endMonthOfYear, endDayOfMonth)
                                startDate = "${calendarStart.get(Calendar.YEAR)}-${calendarStart.get(
                                    Calendar.MONTH) + 1}-${calendarStart.get(Calendar.DAY_OF_MONTH)}"
                                endDate = "${calendarEnd.get(Calendar.YEAR)}-${calendarEnd.get(
                                    Calendar.MONTH) + 1}-${calendarEnd.get(Calendar.DAY_OF_MONTH)}"
                                viewModel.dateTime.postValue(startDate+"\n"+endDate)
                                viewModel.getTracCodeList2(endDate,startDate,"2","",binding.etInput.text.toString(),"",tradeType,"")
                            },
                            calendarEnd.get(Calendar.YEAR), calendarEnd.get(Calendar.MONTH), calendarEnd.get(
                                Calendar.DAY_OF_MONTH)

                        )
                    }
                    // Set minDate for the end picker to prevent selecting a date before the start date
                    endDatePicker?.show()
                    requireActivity().toast(R.string.please_max_date)
                },
                calendarStart.get(Calendar.YEAR), calendarStart.get(Calendar.MONTH), calendarStart.get(
                    Calendar.DAY_OF_MONTH)
            )
        }
        startDatePicker?.show()
        requireActivity().toast(R.string.please_min_date)
    }
    fun setNowDate(){
        viewModel.dateTime.postValue(startDate+"\n"+endDate)
    }
}